package linter.linterjava.custom;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import linter.linterjava.POJO.UtilDTO.PageInfoDTO;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Optional;

import static linter.linterjava.custom.CustomResultType.DATA_NOT_EXIST;

/**
 * @author 北煜
 */
public class ConstantPublicWay {

    /**
     *  没有找到数据
     */
    public static class NoDataFoundException extends RuntimeException {
        public NoDataFoundException(String message) {
            super(message);
        }
    }

    /**
     * 用于进行分页查询
     *
     * @param pageInfoDTO 分页类 -- pageNum，pageSize
     * @param queryWrapper 使用sql语句简化
     * @param mapper 链接数据库层级
     * @param <T> T类型范式
     * @return 返回分页信息
     */
    public static <T> PageInfo<T> getPageInfo(PageInfoDTO pageInfoDTO, QueryWrapper<T> queryWrapper, BaseMapper<T> mapper) {
        int pageSize = Optional.ofNullable(pageInfoDTO.getPageSize()).orElse(10);
        int pageNum = Optional.ofNullable(pageInfoDTO.getPageNum()).orElse(1);
        PageHelper.startPage(pageNum, pageSize);
        List<T> list = mapper.selectList(queryWrapper);
        if (list == null || list.isEmpty()) {
            return new PageInfo<>(list);
        }
        return new PageInfo<>(list);
    }

    /**
     * 获取列表数据
     *
     * @param queryWrapper 使用sql语句简化
     * @param mapper 链接数据库层级
     * @param <T> T类型范式
     * @return 返回列表数据方便处理List
     * @throws NoDataFoundException 没有找到数据
     */
    public static <T> List<T> getList( QueryWrapper<T> queryWrapper, BaseMapper<T> mapper) {
        List<T> list = mapper.selectList(queryWrapper);
        if (list == null || list.isEmpty()) {
            return list;
        }
        return list;
    }

    /**
     * @param url flask端口请求
     * @param params 构造的请求体包含flask需要的参数
     * @return 返回响应体
     */
    public static ResponseEntity<String> sendPostRequest(String url, MultiValueMap<String, Object> params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        return restTemplate.postForEntity(url, requestEntity, String.class);
    }

    /**
     * @param url flask主端口请求
     * @return 返回响应体
     */
    public static String processResponse(String url) {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForObject(url, null, String.class);
    }

}
